import 'dart:convert';
import 'dart:math';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
// import 'package:kerala_lottery/Statistics/views/KL_ChooseTicketNumbers.dart';
// import 'package:kerala_lottery/Statistics/views/KL_digitView.dart';

import '../tools/FL_CustomLoading.dart';
import '../tools/KaL_Config.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'views/KL_ChooseTicketNumbers.dart';
import 'views/KL_digitView.dart';

class KL_AnalyticsPageVC extends StatefulWidget {
  const KL_AnalyticsPageVC({super.key});

  @override
  State<KL_AnalyticsPageVC> createState() => _KL_AnalyticsPageVCState();
}

class _KL_AnalyticsPageVCState extends State<KL_AnalyticsPageVC>
    with AutomaticKeepAliveClientMixin {
  ///保存选号到数据库
  MyTicketEntity _ticketEntity = MyTicketEntity.instan();
  //是否展开了周日期选择
  bool _isExpanded = false;

  ///开奖日期数组
  // late var _drawDateTitles = [];
  // late List<Widget> _headerDigitsViews = [];
  late var _headerDigitsDatas = [];
  late var _formContentDigitsDatas = [];
  //选中号码数组
  late var _selectedNumbers = [];

  late var _firstDigitLetters = [];
  late var _otherDigitNums = [];
  late var _digitStr = [];
  late var _weekdays = [];
  int _currentWeekDayIndex = 0;

  List _draws_titles_left = []; //左边日期
  // late List<Widget> _rightSideWiegets = []; //右侧号码view

  double _rightSideWidth = 0;
  double _leftSideWidth = 80; //左边宽度
  double _cellHeight = 40; //cell高度
  double _cellWidth = 25; //cell宽度

  final ScrollController _formContentController = ScrollController();
  final ScrollController _headerDigitsController = ScrollController();
  final ScrollController _formNumsContentController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _weekdays = KaL_Config.weekdays;
    _firstDigitLetters = KaL_Config.firstDigitLetters;
    _otherDigitNums = KaL_Config.otherDigitNums;
    _digitStr = KaL_Config.digitsStringArr;

    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        title: 'loading...',
      );
    });

    // 延时 1 秒后执行的操作
    Future.delayed(const Duration(milliseconds: 100), () {
      configDatas(_currentWeekDayIndex);
    });

    ///监听滑动联动
    _headerDigitsController.addListener(_updateFormNumsContentController);
    _formNumsContentController.addListener(_updateHeaderDigitsController);
    _formContentController.addListener(_updateFormContentController);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _headerDigitsController.removeListener(_updateFormNumsContentController);
    _formNumsContentController.removeListener(_updateHeaderDigitsController);
    _headerDigitsController.dispose();
    _formContentController.dispose();
    _formNumsContentController.dispose();
  }

  _updateFormContentController() {
    _closeWeekView();
    print('formContentController: ${_formContentController.offset}');
  }

  _updateHeaderDigitsController() {
    _closeWeekView();
    print('headerDigitsController: ${_headerDigitsController.offset}');
    if (_headerDigitsController.offset != _formNumsContentController.offset) {
      _headerDigitsController.jumpTo(_formNumsContentController.offset);
    }
  }

  _updateFormNumsContentController() {
    _closeWeekView();
    print('formNumsContentController: ${_formNumsContentController.offset}');
    if (_formNumsContentController.offset != _headerDigitsController.offset) {
      _formNumsContentController.jumpTo(_headerDigitsController.offset);
    }
  }

  void _closeWeekView() {
    if (_isExpanded) {
      setState(() {
        _isExpanded = false;
      });
    }
  }

  void _toggleExpand() {
    setState(() {
      _isExpanded = !_isExpanded;
    });
  }

  ///save to checker
  _EJ_saveTpChecker() async {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });

    var _saveNumbers = [];
    for (Map element in _selectedNumbers) {
      var number = element['num'];
      _saveNumbers.add(number);
    }

    if (_saveNumbers.isEmpty) {
      BotToast.closeAllLoading();
      return;
    } else if (_saveNumbers.length < KaL_Config.keralaTicketNumCount) {
      BotToast.closeAllLoading();
      BotToast.showText(
          textStyle: const TextStyle(fontSize: 13, color: Colors.white),
          text: 'Please select ${KaL_Config.keralaTicketNumCount} numbers');
      return;
    }

    //补全号码
    var ticketFirstNum = KL_keralaLottoDataModel().nextDrawnModel.ticket_prefix;
    _saveNumbers.insert(0, ticketFirstNum);

    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "Lucky Number",
      "time": currentTimeMillis,
      "numbers": jsonEncode(_saveNumbers),
    };

    ///保存选号
    // int save = await ticketEntity.insert(tickets);
    await _ticketEntity.insert(tickets);
    Future.delayed(const Duration(milliseconds: 300), () {
      BotToast.closeAllLoading();
      BotToast.showText(text: 'Save successfully!');
    });
  }

  void configDatas(int weekdayIndex) async {
    await _changeDrawDate(weekdayIndex);
    await _configFormDatas(weekdayIndex);
    await _configHeaderDatas();

    setState(() {
      //自动滑动到最底
      Future.delayed(const Duration(milliseconds: 300), () {
        BotToast.closeAllLoading();
        _formContentController
            .jumpTo(_formContentController.position.maxScrollExtent);
      });
    });
  }

  ///切换日期
  _changeDrawDate(int index) async {
    _draws_titles_left =
        await KL_keralaLottoDataModel().getweekdayDrawDatas(index);
    debugPrint('_draws_titles_left: $_draws_titles_left');
    return _draws_titles_left;
  }

  ///砌头部数据和view
  _configHeaderDatas() async {
    _headerDigitsDatas.clear();
    Map firstDigitMap = {'title': '1st Digit', 'nums': _firstDigitLetters};
    _headerDigitsDatas.add(firstDigitMap);
    _rightSideWidth += _firstDigitLetters.length * _cellWidth;

    for (var i = 1; i < 7; i++) {
      var digitStr = _digitStr[i];
      var title = '$digitStr Digit';
      Map digitMap = {'title': title, 'nums': _otherDigitNums};

      ///计算右边表格总宽度
      _rightSideWidth += _otherDigitNums.length * _cellWidth;
      _headerDigitsDatas.add(digitMap);
    }

    debugPrint('_headerDigitsDatas: $_headerDigitsDatas');
    return _headerDigitsDatas;
  }

  _configFormDatas(int weekdayIndex) async {
    _formContentDigitsDatas =
        await KL_keralaLottoDataModel().KL_getAnalyticsResults(weekdayIndex);
    debugPrint('_formContentDigitsDatas: $_formContentDigitsDatas');
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: _appBar(),
      body: Container(
        color: KaL_Config.KaL_pageBgColor,
        child: _draws_titles_left.isEmpty
            ? null
            : Column(
                children: [
                  formView(),
                  bottomView(),
                ],
              ),
      ),
    );
  }

  Widget formView() {
    return Expanded(
      child: Stack(
        alignment: Alignment.topLeft,
        children: [
          Column(
            children: [
              formHeaderView(),
              formContentView(),
            ],
          ),
          Positioned(
            top: 34,
            left: 10,
            child: weekListView(),
          ),
        ],
      ),
    );
  }

  Widget buildContentLeftList() {
    return ListView.builder(
      physics: const NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // 适应高度
      itemCount: _draws_titles_left.length,
      itemBuilder: (context, index) {
        bool isLastLine = index == _draws_titles_left.length - 1;
        return leftSideView(_draws_titles_left[index], isLastLine);
      },
    );
  }

  Widget buildContentRightList() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      physics: const NeverScrollableScrollPhysics(), // 禁止滚动
      shrinkWrap: true, // 适应高度
      itemCount: _formContentDigitsDatas.length,
      itemBuilder: (context, index) {
        bool isLastLine = index == _formContentDigitsDatas.length - 1;
        if (!isLastLine) {
          return rightSideView(index, isLastLine: isLastLine);
        } else {
          List digitsDatas = _formContentDigitsDatas[index];
          return KlChooseticketnumbers(
            key: ValueKey(index),
            numberDatas: digitsDatas,
            callback: (selectedNumber) {
              print('选中---$selectedNumber');
              _selectedNumbers.clear();
              for (List element in selectedNumber.values) {
                if (element.isNotEmpty) {
                  _selectedNumbers.addAll(element);
                }
              }
              setState(() {});
            },
          );
        }
      },
    );
  }

  Widget formContentView() {
    return Expanded(
      child: CustomScrollView(
        physics: const ClampingScrollPhysics(), //禁止惯性
        controller: _formContentController,
        slivers: [
          SliverToBoxAdapter(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                // 自定义左侧列表的宽度
                Container(
                  color: Colors.white,
                  width: 80, // 设置左侧列表宽度
                  child: buildContentLeftList(),
                ),

                // 自定义右侧列表的宽度
                Expanded(
                  child: SingleChildScrollView(
                    controller: _formNumsContentController,
                    physics: const ClampingScrollPhysics(), //禁止惯性
                    scrollDirection: Axis.horizontal,
                    child: SizedBox(
                      width: _rightSideWidth, // 设置右侧列表的宽度
                      child: buildContentRightList(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget rightSideView(int index, {bool isLastLine = false}) {
    List digitsDatas = _formContentDigitsDatas[index];
    List<Widget> _rowViews = [];
    for (int i = 0; i < digitsDatas.length; i++) {
      Map element = digitsDatas[i];
      List _numbers = element['nums'] ?? [];

      int oddIndex = i % 2;
      Color bgColor = oddIndex == 0 ? HexColor('#e6fff0') : HexColor('#ffecf5');
      Color rightNumColor =
          oddIndex == 0 ? HexColor('#168a43') : HexColor('#d22f7d');

      ///
      _rowViews.add(KlDigitview(
        key: ValueKey(_numbers[i]),
        digitMap: element,
        isTheLast: isLastLine,
        bgColor: bgColor,
        rightNumColor: rightNumColor,
      ));
    }
    return Wrap(
      children: _rowViews,
    );
  }

  Widget leftSideView(String title, bool isLastLine) {
    Alignment alignment = Alignment.center;
    double viewH = _cellHeight;
    double _titleOffset = 0;
    if (isLastLine) {
      alignment = Alignment.topCenter;
      viewH = viewH * 2;
      _titleOffset = 8.0;
    }
    return Container(
      alignment: alignment,
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
          right: BorderSide(color: HexColor('#dddddd'), width: 1),
        ),
        // color: Colors.white,
      ),
      width: _cellWidth,
      height: viewH,
      child: Padding(
        padding: EdgeInsets.only(top: _titleOffset),
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 10,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  Widget formHeaderView() {
    return Row(children: [
      drawsView(),
      headerDigitsView(),
    ]);
  }

  Widget headerDigitsView() {
    return Expanded(
      child: Container(
        // color: Colors.yellow,
        width: _rightSideWidth,
        height: _cellHeight * 2,
        child: ListView.builder(
            controller: _headerDigitsController,
            physics: const ClampingScrollPhysics(),
            scrollDirection: Axis.horizontal,
            itemCount: _headerDigitsDatas.length,
            itemBuilder: (context, index) {
              var data = _headerDigitsDatas[index];
              return KlDigitview(digitMap: data);
            }),
      ),
    );
  }

  Widget drawsView() {
    return SizedBox(
      width: _leftSideWidth,
      height: _cellHeight * 2,
      child: Column(children: [
        Container(
          height: _cellHeight,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
              top: BorderSide(color: HexColor('#dddddd'), width: 1),
              bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
              right: BorderSide(color: HexColor('#dddddd'), width: 1),
            ),
          ),
          child: GestureDetector(
            onTap: () {
              debugPrint('展开');
              _toggleExpand();
            },
            child: Container(
              alignment: Alignment.center,
              margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),
              decoration: BoxDecoration(
                color: HexColor('#eeeeee'),
                borderRadius: _isExpanded
                    ? BorderRadius.only(
                        topLeft: Radius.circular(_cellHeight * 0.5),
                        topRight: Radius.circular(_cellHeight * 0.5),
                      )
                    : BorderRadius.all(Radius.circular(_cellHeight * 0.5)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _weekdays[_currentWeekDayIndex],
                    style: TextStyle(
                        color: HexColor('#666666'),
                        fontWeight: FontWeight.w400,
                        fontSize: 12),
                  ),
                  Icon(
                    _isExpanded
                        ? Icons.keyboard_arrow_up
                        : Icons.keyboard_arrow_down,
                    color: HexColor('#666666'),
                    size: 16,
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          height: _cellHeight,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
              right: BorderSide(color: HexColor('#dddddd'), width: 1),
              bottom: BorderSide(color: HexColor('#dddddd'), width: 1),
            ),
          ),
          child: const Text('Draws',
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.w400,
                fontSize: 12,
              )),
        ),
      ]),
    );
  }

  /// 周期筛选列表
  Widget weekListView() {
    return AnimatedSize(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      child: Container(
        width: 59,
        height: _isExpanded ? 220 : 0,
        decoration: BoxDecoration(
          color: HexColor('#eeeeee'),
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(_cellHeight * 0.5),
              bottomRight: Radius.circular(_cellHeight * 0.5)),
        ),
        child: _isExpanded
            ? ListView.builder(
                physics: const ClampingScrollPhysics(),
                itemCount: _weekdays.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () {
                      debugPrint('选择了 ${_weekdays[index]}');
                      setState(() {
                        _isExpanded = false;
                        _currentWeekDayIndex = index;
                      });

                      BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
                        return FLCustomLoading(
                          title: 'loading...',
                        );
                      });

                      Future.delayed(const Duration(milliseconds: 100), () {
                        configDatas(index);
                      });
                    },
                    child: Container(
                      height: 34,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        border: Border(
                          top: BorderSide(color: HexColor('#dddddd'), width: 1),
                        ),
                      ),
                      child: Text(
                        _weekdays[index],
                        style: const TextStyle(
                          fontWeight: FontWeight.w400,
                          fontSize: 10,
                        ),
                      ),
                    ),
                  );
                },
              )
            : null,
      ),
    );
  }

  Widget bottomView() {
    var regularNumCount = KaL_Config.keralaTicketNumCount;
    var _selectedNumCount = _selectedNumbers.length;
    return Container(
      height: 45,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Text(
            'Choose $regularNumCount numbers to save($_selectedNumCount/$regularNumCount)',
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w400,
            ),
          ),
          const Spacer(),
          OutlinedButton(
            onPressed: () {
              debugPrint('Save to Checker');
              _EJ_saveTpChecker();
            },
            style: ButtonStyle(
                backgroundColor:
                    WidgetStatePropertyAll(KaL_Config.KaL_MainColor),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                side: WidgetStateProperty.all(
                    //边框
                    BorderSide(
                  color: KaL_Config.KaL_MainColor, //颜色
                  width: 1.0, //宽度
                )),
                minimumSize: const WidgetStatePropertyAll(Size(40, 35))),
            child: const Text(
              "Save to Checker",
              style: TextStyle(fontWeight: FontWeight.w400, fontSize: 13),
            ),
          ),
          const SizedBox(width: 15),
        ],
      ),
    );
  }

  PreferredSizeWidget _appBar() {
    return AppBar(
      title: Image.asset(
        'assets/sys_imgs/DearLottery Logo.png',
        width: 160,
        height: 50,
      ),
      backgroundColor: Colors.white,
      foregroundColor: KaL_Config.KaL_MainColor,
      centerTitle: true,
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
